package com.xdh.zzqh.ui.dialog

import android.view.ViewGroup.LayoutParams
import android.widget.Button
import com.xdh.zzqh.R
import com.xdh.zzqh.store.Product
import com.xdh.zzqh.ui.view.ProductParts
import com.xdh.zzqh.utils.onClick
import com.xdh.zzqh.utils.showToast
import com.xdh.zzqh.utils.stringById
import kotlinx.coroutines.CompletableDeferred

class CreateProductDialog : DraggableWindow(800, LayoutParams.WRAP_CONTENT, R.layout.dialog_product_create, true) {

    private val productParts = view.findViewById<ProductParts>(R.id.id_product_parts)
    private val btnCreate = view.findViewById<Button>(R.id.id_product_btn_create)

    suspend fun waitCreate(): Product {
        var flag = false
        val complete = CompletableDeferred<Product>()
        window.setOnDismissListener {
            if (flag) {
                return@setOnDismissListener
            }
            complete.completeExceptionally(IllegalStateException(stringById(R.string.qu_xiao_chuang_jian)))
        }

        showCenter(-100)

        btnCreate.onClick {
            try {
                val product = productParts.product()
                flag = true
                complete.complete(product)
                dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
                showToast(e.message ?: stringById(R.string.cuo_wu))
            }
        }

        return complete.await()
    }
}